package com.atguigu.juc.day02.rw;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Demo01ReadAndRead {

    // 创建读写锁对象
    private ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    // 获取读锁对象
    private Lock readLock = readWriteLock.readLock();

    // 声明一个方法执行读操作
    public void doReadOperation() {

        try {
            // 加读锁
            readLock.lock();

            System.out.println(Thread.currentThread().getName() + " 线程开始执行读操作。");

            TimeUnit.SECONDS.sleep(5);

            System.out.println(Thread.currentThread().getName() + " 线程结束执行读操作。");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 解读锁
            readLock.unlock();
        }

    }

    public static void main(String[] args) {

        Demo01ReadAndRead demo = new Demo01ReadAndRead();

        for (int i = 0; i < 10; i++) {
            new Thread(()->{

                demo.doReadOperation();

            }, "thread-" + i).start();
        }

    }

}
